package com.xjl.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 测试信号量
 * @author xiaojinlu1990@163.com
 * date 2019-12-26
 */
@Slf4j
public class SemaPhoreExample {
    private final static int totelCount = 1000;
    private final static int threadCount = 20;

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount);

        for (int i = 0; i < totelCount; i++) {

            final int finalI = i;
            service.execute(() ->{
                try {
                    semaphore.acquire();//获得一个许可

                    waitThread(finalI);
                    semaphore.release();//释放一个许可
                } catch (InterruptedException e
                        ) {
                    e.printStackTrace();
                }finally {
                    //固定语法适用范围很广泛
                }
            });
        }
        service.shutdown();
    }

    private static void waitThread(int i) {
        try {
            log.info("{}",i);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {

        }

    }

}
